import { Button, message, Modal } from 'antd';
import Search from 'antd/lib/input/Search';
import Table, { ColumnsType } from 'antd/lib/table';
import { checkPermission } from 'permission/Index';
import React from 'react';
import { Result } from 'admin/schema/Result';
import { CorporateInfo } from '../../../schema/Corporate';
import { deleteCorporate, getCorporate, getCorporateList } from '../../../servers/servers';
import { clearNull, deleteRowChangePageNum, getTableIndex } from '../../../../utils/tools';
import { CorporateCheckDetail } from './component/CorporateCheckDetail';
import { CorporateOperationDrawer } from './component/CorporateOperationDrawer';
import './style.scss';

/**
 * 企业管理state
 */
interface CorporateState {
  // 公司名称
  companyName: string;
  // 新增企业抽屉控件显隐
  operationVisible: boolean;
  // 展示在table的数据
  tableData: CorporateInfo[];
  // 详情对话框是否显示
  detailVisible: boolean;
  // 当前选中所要查看详情的数据
  current?: CorporateInfo;
  // 分页相关数据
  pageInfo: {
    pageTotal: number;
    pageNum: number;
    pageSize: number;
  };
  tableLoading: boolean;
}

/**
 * 企业管理页
 */
class Corporate extends React.Component<{}, CorporateState> {
  /**
   * table列头
   * 因为table列头相对固定，不需要响应式地修改视图，所以记录在类的私有属性中而不是react state中，轻量的state利于提升性能
   */
  private columns: ColumnsType<CorporateInfo>;

  /**
   * 企业操作
   */
  private DrawRef: React.RefObject<CorporateOperationDrawer>;

  private compMounted: boolean;

  private fetchListPromise: ((data: any) => Promise<Result<CorporateInfo[]>>) | null;

  constructor(props: {}) {
    super(props);
    this.DrawRef = React.createRef();
    this.compMounted = true;
    this.fetchListPromise = getCorporateList;
    this.state = {
      companyName: '',
      detailVisible: false,
      operationVisible: false,
      current: undefined,
      tableData: [],
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: false,
    };
    this.columns = [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        key: 'index',

        render: (text, record, index) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      },
      ...tableColumn,
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        width: 200,
        fixed: 'right',
        render: (text, record, index) => (
          <>
            <Button
              type="link"
              onClick={() => {
                this.checkDetail(record);
              }}
            >
              详情
            </Button>
            {checkPermission('/account/company/modify') && (
              <Button
                type="link"
                onClick={() => {
                  this.modify(record);
                }}
              >
                编辑
              </Button>
            )}
            {checkPermission('/account/company/delete') && (
              <Button
                type="link"
                onClick={() => {
                  this.deleteRecord(record);
                }}
              >
                删除
              </Button>
            )}
          </>
        ),
      },
    ];
  }

  public componentDidMount() {
    this.compMounted = true;
    this.fetchList();
  }

  componentWillUnmount() {
    this.compMounted = false;
    this.fetchListPromise = null;
  }

  /**
   * 根据企业名称查询列表
   */
  private searchCorporate(name: string) {
    this.setState(
      {
        companyName: name.trim(),
      },
      () => {
        this.jumpPage(1);
      }
    );
  }

  /**
   * 查看企业详情
   */
  private checkDetail(record: CorporateInfo) {
    getCorporate(record.companyId as number)
      .then(res => {
        this.setState({
          current: res.data,
          detailVisible: true,
        });
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * 打开新建企业弹窗
   */
  private create() {
    this.DrawRef.current?.open('create');
  }

  /**
   * 编辑企业交互
   */
  private modify(record: CorporateInfo) {
    getCorporate(record.companyId as number)
      .then(res => {
        this.DrawRef.current?.open('modify');
        this.DrawRef.current?.setValue(res.data);
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * 删除企业交互
   */
  private deleteRecord(record: CorporateInfo) {
    Modal.confirm({
      content: '删除企业后无法恢复，确定删除吗',
      onOk: () => {
        deleteCorporate(record.companyId as number)
          .then(res => {
            message.success('删除成功');
            this.deleteFresh(1);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }

  /**
   * 获取数据
   */
  private fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { companyName, pageInfo } = this.state;
    this.fetchListPromise &&
      this.fetchListPromise(
        clearNull({
          companyName: companyName,
          pageNo: pageInfo.pageNum,
          pageSize: pageInfo.pageSize,
        })
      )
        .then(res => {
          this.setState({
            tableLoading: false,
          });
          pageInfo.pageTotal = res.count as number;
          if (this.compMounted) {
            this.setState({
              tableData: res.data,
              pageInfo: pageInfo,
            });
          }
        })
        .catch(error => {
          this.setState({
            tableLoading: false,
          });
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
  }

  /**
   * 删除-数据后更新
   */
  private deleteFresh(size: number) {
    const { pageTotal, pageNum, pageSize } = this.state.pageInfo;
    const newPageNum = deleteRowChangePageNum(size, pageTotal, pageNum, pageSize);
    this.setState(
      {
        pageInfo: {
          pageTotal,
          pageSize,
          pageNum: newPageNum,
        },
      },
      () => {
        this.fetchList();
      }
    );
  }

  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }

  render() {
    const {
      tableData,
      tableLoading,
      pageInfo: { pageNum, pageSize, pageTotal },
      current,
      detailVisible,
    } = this.state;

    return (
      <>
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Search
              className="mgr-header-search"
              placeholder="请输入企业名称"
              enterButton="搜索"
              onSearch={value => this.searchCorporate(value)}
            />
          </div>
          <div className="mgr-header-right">
            {checkPermission('/account/company/add') && (
              <Button
                type="primary"
                onClick={() => {
                  this.create();
                }}
              >
                新建企业
              </Button>
            )}
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            scroll={{ x: 'max-content' }}
            columns={this.columns}
            dataSource={tableData}
            rowKey={columns => columns.contactNumber as string}
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <CorporateOperationDrawer
          ref={this.DrawRef}
          callback={id => {
            id ? this.fetchList() : this.jumpPage(1);
          }}
        />
        <CorporateCheckDetail
          visible={detailVisible}
          corporateInfo={current}
          onClose={() => {
            this.setState({ detailVisible: false });
          }}
        />
      </>
    );
  }
}

const tableColumn: ColumnsType<CorporateInfo> = [
  {
    title: '企业名称',
    dataIndex: 'companyName',
    key: 'companyName',
    width: 200,
  },
  {
    title: '联系人姓名',
    dataIndex: 'contactName',
    key: 'contactName',
    width: 120,
  },
  {
    title: '手机号',
    dataIndex: 'contactNumber',
    key: 'contactNumber',
    width: 100,
  },
  {
    title: '纳税人识别号',
    dataIndex: 'taxpayerIdentityNumber',
    key: 'taxpayerIdentityNumber',
  },
  {
    title: '企业地址',
    dataIndex: 'companyAddress',
    key: 'companyAddress',
    width: 300,
  },
  {
    title: '最大任务并发',
    dataIndex: 'maxTask',
    key: 'maxTask',
    width: 120,
  },
  {
    title: '最大呼叫并发',
    dataIndex: 'maxCall',
    key: 'maxCall',
    width: 120,
  },
];

export default Corporate;
